package com.weijian.utils;

import com.weijian.dal.dataobject.Article;
import com.weijian.service.ArticleService;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
public class ParseWordFileUtil {


    public static boolean isValidWordFile(List<MultipartFile> files) {
        if (files == null || files.isEmpty()) {
            return false;
        }
        String firstFileName = files.get(0).getOriginalFilename();
        if (firstFileName == null) {
            return false;
        }
        String firstFileExtension = firstFileName.substring(firstFileName.lastIndexOf("."));
        for (MultipartFile file : files) {
            String name = file.getOriginalFilename();
            if (name == null) {
                return false;
            }
            String currentFileExtension = name.substring(name.lastIndexOf("."));
            if (!currentFileExtension.equalsIgnoreCase(firstFileExtension)) {
                return false;
            }
        }
        return true;
    }


    // 解析.docx文件但不存储
    public static String parseDocxFile(MultipartFile file) throws IOException {
        XWPFDocument doc = new XWPFDocument(file.getInputStream());
        return doc.getParagraphs().stream().map(XWPFParagraph::getText).collect(Collectors.joining("\n"));
    }

    // 解析.doc文件但不存储
    public static String parseDocFile(MultipartFile file) throws IOException {
        HWPFDocument doc = new HWPFDocument(file.getInputStream());
        return doc.getDocumentText();
    }

    // 批量解析.docx文件存到数据库，并且返回内容
    public static void parseDocxFilesAndStore(List<MultipartFile> files,
                                              ArticleService ArticleService) throws IOException {
        List<Article> ArticleList = new ArrayList<>();

        for (MultipartFile file : files) {
            XWPFDocument doc = new XWPFDocument(file.getInputStream());
            // 提取标题和内容
            String title = extractDocxTitle(doc);
            String content = doc.getParagraphs().stream().map(XWPFParagraph::getText).collect(Collectors.joining("\n"));
            // 根据标题判断是否文件存在
            if (exist(ArticleService, title)) {
                continue;
            }
            // 创建新的 Article 对象
            Article newArticle = new Article();
            newArticle.setTitle(title);
            newArticle.setContent(content);
            ArticleList.add(newArticle);
        }
        // 批量存储到数据库
        ArticleService.saveBatch(ArticleList);
    }


    // 解析.doc文件并且存到数据库, 并且返回内容
    public static void parseDocFilesAndStore(List<MultipartFile> files,
                                             ArticleService ArticleService) throws IOException {
        List<Article> ArticleList = new ArrayList<>();
        for (MultipartFile file : files) {
            HWPFDocument doc = new HWPFDocument(file.getInputStream());
            // 提取标题和内容
            String title = extractDocTitle(doc);
            String content = doc.getDocumentText();
            // 根据标题判断是否文件存在
            if (exist(ArticleService, title)) {
                continue;
            }
            // 设置标题和内容
            Article newArticle = new Article();
            newArticle.setTitle(title);
            newArticle.setContent(content);
            ArticleList.add(newArticle);
        }
        // 批量存储到数据库
        ArticleService.saveBatch(ArticleList);
    }

    private static boolean exist(ArticleService ArticleService, String title) {
        return ArticleService.lambdaQuery().eq(Article::getTitle, title).exists();
    }

    // 提取.docx文件的标题
    private static String extractDocxTitle(XWPFDocument doc) {
        StringBuilder titleBuilder = new StringBuilder();
        int titleFontSize = -1; // 初始字号为 -1

        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            String paragraphText = paragraph.getText().trim();
            // 跳过空行
            if (paragraphText.isEmpty() || paragraphText.isBlank()) {
                continue;
            }
            // 获取段落的第一个文本运行的字号
            int currentFontSize = -1;
            if (!paragraph.getRuns().isEmpty()) {
                currentFontSize = paragraph.getRuns().get(0).getFontSize();
            }
            // 初始化标题字号
            if (titleFontSize == -1 && currentFontSize != -1) {
                titleFontSize = currentFontSize;
            }
            // 判断标题是否结束
            if (currentFontSize == -1 || currentFontSize != titleFontSize) {
                break; // 标题结束，立即退出循环
            }
            titleBuilder.append(paragraphText);

        }
        return "《" + titleBuilder.toString().trim() + "》";
    }


    // 提取.doc文件的标题
    private static String extractDocTitle(HWPFDocument doc) {
        StringBuilder titleBuilder = new StringBuilder();
        int titleFontSize = -1;

        for (int i = 0; i < doc.getRange().numParagraphs(); i++) {
            String paragraphText = doc.getRange().getParagraph(i).text().trim();
            if (paragraphText.isEmpty() || paragraphText.isBlank()) {
                continue;
            }
            int currentFontSize = doc.getRange().getParagraph(i).getCharacterRun(0).getFontSize();
            if (titleFontSize == -1) {
                titleFontSize = currentFontSize;
            }
            if (currentFontSize != titleFontSize) {
                break;
            }
            titleBuilder.append(paragraphText);

        }
        return "《" + titleBuilder.toString().trim() + "》";
    }
}
